<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="岗位名称" prop="post">
        <el-input v-model="queryParams.post" placeholder="请输入岗位名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="单位名称" prop="unit">
        <el-input v-model="queryParams.unit" placeholder="请输入单位名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="审核状态" prop="approveStatus">
        <el-select v-model="queryParams.approveStatus" placeholder="请选择审核状态" clearable style="width:200px;" @change="handleApproveStatusChange">
          <el-option v-for="dict in bus_signup_approve_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="exportToExcel" v-hasPermi="['bus:signup:export']">导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="signupList" border fit highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" width="70" />
      <el-table-column label="地市信息" prop="cityName" width="120" />
      <el-table-column label="岗位名称" prop="post" width="220" />
      <el-table-column label="单位名称" prop="unit" width="180" />
      <el-table-column label="姓名" prop="name" width="100" />
      <el-table-column label="性别" prop="gender" width="80" :formatter="formatGender" />
      <el-table-column label="所属学院" prop="college" width="130" />
      <el-table-column label="专业" prop="major" width="150" />
      <el-table-column label="年级" prop="grade" width="100" />
      <el-table-column label="出生日期" prop="birthday" width="120" :formatter="formatBirthday" />
      <el-table-column label="审核状态" prop="approveStatus" width="100">
        <template v-slot:default="scope">
          <el-tag :type="getApproveStatusTagType(scope.row.approveStatus)">
            {{ getApproveStatusLabel(scope.row.approveStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="附件" width="100" align="center">
        <template v-slot:default="scope">
          <div v-if="scope.row.fileUrl">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleViewFile(scope.row.fileUrl)">
              查看
            </el-button>
          </div>
          <div v-else>无附件</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template v-slot:default="scope">
            <el-space>
              <el-button link type="primary" @click="handleDetail(scope.row)" v-hasPermi="['bus:signup:view']">查看详情</el-button>
            </el-space>
          </template>
        </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="getList"
      @update:page="(val) => queryParams.pageNum = val"
      @update:limit="(val) => queryParams.pageSize = val"
    />

    <!-- 审核对话框 -->
    <el-dialog :title="title" v-model="approveOpen" width="500px" append-to-body>
      <el-form ref="approveRef" :model="approveForm" :rules="rules" label-width="80px">
        <el-form-item label="审核状态" prop="approveStatus">
          <el-radio-group v-model="approveForm.approveStatus">
            <el-radio v-for="item in approveStatusOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="审核意见" prop="approveReview" required>
          <el-input v-model="approveForm.approveReview" type="textarea" :rows="4" :maxlength="200" show-word-limit
            placeholder="请输入审核意见" @keydown="handleKeydown" @input="handleInput" />
        </el-form-item>
      </el-form>
      <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitApproveForm">确 定</el-button>
            <el-button @click="cancelApprove">取 消</el-button>
          </div>
        </template>
    </el-dialog>

    <!-- 查看审核详情对话框 -->
    <el-dialog title="审核详情" v-model="detailOpen" width="500px" append-to-body>
      <el-form :model="detailForm" label-width="80px">
        <el-form-item label="用户姓名:">
          <span>{{ detailForm.name }}</span>
        </el-form-item>
        <el-form-item label="审核状态:">
          <el-tag :type="getApproveStatusTagType(detailForm.approveStatus)">
            {{ getApproveStatusLabel(detailForm.approveStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="审核意见:">
          <el-input 
            type="textarea" 
            :rows="4" 
            v-model="detailForm.approveReview" 
            readonly>
          </el-input>
        </el-form-item>
        <el-form-item label="审核时间:">
          <span>{{ parseTime(detailForm.approveTime, '{y}-{m}-{d}') }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 岗位详情弹窗 -->
    <el-dialog title="岗位详情" v-model="showContentDialog" width="800px" :style="{ maxWidth: '90vw' }" append-to-body>
      <div v-html="contentDetail" style="word-break: break-all; max-height: 500px; overflow: auto; padding-right: 8px;">
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showContentDialog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listSignupWithRequire, updateSignup, exportSignupData, getSignup, getRequireDetail } from '@/api/bus/signup.js'
import axios from 'axios'
import { getApprove, updateApprove } from '@/api/signup/approve'
import Pagination from '@/components/Pagination'
import { nextTick } from 'vue'


console.log('开始加载signup/index.vue组件')

export default {
  name: 'BusSignup',
  components: {
    Pagination
  },

  data() {
    return {
      loading: false,
      total: 0,
      signupList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        post: '',
        unit: '',
        name: '',
        approveStatus: undefined
      },
      // 审核状态字典数据（与signup/approve/index.vue保持一致）
      bus_signup_approve_status: [
        { value: 0, label: '待审核' },
        { value: 1, label: '已通过' },
        { value: 2, label: '已拒绝' }
      ],
      // 审核状态映射关系
      approveStatusMap: {
        0: {
          label: '待审核',
          type: 'info'
        },
        1: {
          label: '已通过',
          type: 'success'
        },
        2: {
          label: '已拒绝',
          type: 'danger'
        }
      },

      // 导出选项
        selectedRows: [], // 选中的行数据
      // 审核弹窗相关
      approveOpen: false,
      title: '',
      approveForm: {},
      rules: {
        approveReview: [{
          required: true,
          message: '审核意见不能为空',
          trigger: 'blur'
        }]
      },
      approveStatusOptions: [{
          label: '通过',
          value: 1
        },
        {
          label: '拒绝',
          value: 2
        }
      ],
      // 详情弹窗相关
      detailOpen: false,
      detailForm: {},
      // 仿require页面的详情弹窗
      showContentDialog: false,
      contentDetail: ''
    }
  },
  created() {
    // 从URL参数中获取审核状态
    const route = this.$route;
    if (route.query.approveStatus !== undefined) {
      this.queryParams.approveStatus = parseInt(route.query.approveStatus, 10);
      console.log('从URL参数获取审核状态:', this.queryParams.approveStatus);
    }
    this.getList()
  },
  mounted() {
    // 确保审核状态选择框正确初始化
    this.$nextTick(() => {
      if (this.queryParams.approveStatus !== undefined && this.queryParams.approveStatus !== null) {
        console.log('初始化审核状态:', this.queryParams.approveStatus);
      }
    });
  },
  methods: {
      // 处理选择变化
        handleSelectionChange(selection) {
          this.selectedRows = selection;
        },

        // 导出为Excel
        exportToExcel() {
          const hasSelected = this.selectedRows.length > 0;
          const confirmMessage = hasSelected ? '确定要导出选中的数据吗？' : '未选择数据，是否导出所有数据？';

          this.$confirm(confirmMessage, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 构造导出数据参数
            const data = { ...this.queryParams };
            // 如果有选中数据，则添加signupIds参数
            if (hasSelected) {
              const ids = this.selectedRows.map(row => row.signupId);
              data.signupIds = ids;
            }

            // 使用API模块中的exportSignupData函数
            exportSignupData(data).then(response => {
              console.log('导出响应:', response)
              // 处理导出成功的响应
              const blob = new Blob([response], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
              })
              const fileName = '报名数据.xlsx'
              const link = document.createElement('a')
              link.href = URL.createObjectURL(blob)
              link.download = fileName
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link)
              URL.revokeObjectURL(link.href) // 释放URL对象
              this.$message.success('导出成功')
            }).catch(error => {
              console.error('导出失败:', error)
              this.$message.error('导出失败，请重试')
            })
          }).catch(() => {
            // 用户取消操作
          })
        },
      
      // 格式化参数为URL查询字符串
      formatParams(params) {
        return Object.keys(params)
          .filter(key => params[key] !== undefined && params[key] !== null)
          .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
          .join('&')
      },

      
      formatGenderForExport(gender) {
        if (gender === 1 || gender === '1') return '男'
        if (gender === 2 || gender === '2') return '女'
        if (gender === 0 || gender === '0') return '其他'
        return ''
      },

      getList() {
      this.loading = true
      console.log('调用API参数:', this.queryParams, '参数类型: pageNum=', typeof this.queryParams.pageNum, 'pageSize=', typeof this.queryParams.pageSize)
      listSignupWithRequire(this.queryParams).then(response => {
          console.log('API响应完整结构:', JSON.stringify(response, null, 2))
          // 检查响应数据结构
          if (!response) {
            this.signupList = []
            this.total = 0
            console.error('API响应为空')
          } else if (response.rows && response.total !== undefined) {
            // 直接使用response中的rows和total
            this.signupList = response.rows
            this.total = response.total
            console.log('使用响应根级别的分页数据, total:', response.total, 'rows.length:', response.rows.length)
          } else if (response.data && response.data.rows && response.data.total !== undefined) {
            // 使用data中的rows和total
            this.signupList = response.data.rows
            this.total = response.data.total
            console.log('使用标准分页数据结构, total:', response.data.total, 'rows.length:', response.data.rows.length)
          } else if (response.data && Array.isArray(response.data)) {
            // 如果data直接返回了列表
            this.signupList = response.data
            this.total = response.data.length
            console.log('使用直接返回的列表数据, total:', response.data.length)
            console.log('使用直接返回的列表数据')
          } else {
            this.signupList = []
            this.total = 0
            console.error('API返回数据格式不正确，预期包含rows和total字段或直接返回列表')
            console.log('响应内容:', response)
          }
          console.log('搜索结果数量:', this.signupList.length)
          this.loading = false
        }).catch(error => {
        console.error('API调用失败:', error)
        this.loading = false
      })
    },
    handleQuery() {
         this.queryParams.pageNum = 1
         console.log('搜索参数:', this.queryParams)
         console.log('审核状态值:', this.queryParams.approveStatus, '类型:', typeof this.queryParams.approveStatus)
         console.log('审核状态选项:', this.bus_signup_approve_status)
         this.getList()
    },

    // 处理审核状态变化
    handleApproveStatusChange(value) {
      this.queryParams.approveStatus = value;
      console.log('审核状态变更为:', value, '类型:', typeof value);
      // 立即触发查询
      this.handleQuery();
    },
    
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.queryParams.approveStatus = undefined
      this.getList()
    },
    // 查看详情（弹窗方式）
    showContentDetail(row) {
      // 获取岗位需求详情
      getRequireDetail(row.requireId).then(response => {
        const data = response.data || {};
        // 构建详情内容
        let unit = data.unit || '';
        let project = data.project || '';
        let post = data.post || '';
        let content = data.content || '';
        let intention = data.intention || '';
        let quantity = data.quantity !== undefined && data.quantity !== null ? data.quantity : '';
        let recruited = data.recruited !== undefined && data.recruited !== null ? data.recruited : '';
        let contact = data.contact || '';
        let number = data.number || '';
        let remark = data.remark || '';
        let expirationTime = data.expirationTime ? this.parseTime(data.expirationTime, '{y}-{m}-{d}') : '';
        let latestApproveReview = data.latestApproveReview || '';

        // 构建HTML内容
        this.contentDetail = `
<div>
  <div class="content-detail-img-box" style="margin-bottom: 16px; border: 1px solid #000; border-radius: 4px; padding: 12px 16px; background: #fff;">
    <div style="margin-bottom: 8px;"><strong>单位名称：</strong>${unit}</div>
    <div style="margin-bottom: 8px;"><strong>规划编制、重点课题：</strong>${project}</div>
    <div style="margin-bottom: 8px;"><strong>岗位名称：</strong>${post}</div>
  </div>
  <div class="content-detail-img-box" style="margin-bottom: 16px; border: 1px solid #000; border-radius: 4px; padding: 12px 16px; background: #fff;">
    <strong>课题研究目标：</strong><br>
    <div class="ql-editor">${content}</div>
  </div>
  <div style="margin-bottom: 8px;"><strong>意向高校或专业：</strong>${intention}</div>
  <div style="margin-bottom: 8px;"><strong>岗位数量：</strong>${quantity}</div>
  <div style="margin-bottom: 8px;"><strong>已招收：</strong>${recruited}</div>
  <div style="margin-bottom: 8px;"><strong>联系人：</strong>${contact}</div>
  <div style="margin-bottom: 8px;"><strong>联系方式：</strong>${number}</div>
  <div style="margin-bottom: 8px;"><strong>备注：</strong>${remark}</div>
  <div style="margin-bottom: 8px;"><strong>过期时间：</strong>${expirationTime}</div>
  <div style="margin-bottom: 8px;"><strong>最新审核意见：</strong>${latestApproveReview}</div>
</div>
<style>
  .content-detail-img-box img { max-width: 100%; height: auto; display: block; margin: 0 auto; }
</style>
<!-- 引入 Quill 编辑器样式，仅在本页生效 -->
<style src="@vueup/vue-quill/dist/vue-quill.snow.css"></style>
`;
        this.showContentDialog = true;
      }).catch(error => {
        console.error('获取岗位详情失败:', error);
        this.$message.error('获取详情失败，请重试');
      });
    },

    // 格式化性别用于详情展示
    formatGenderForDetail(gender) {
      if (gender === 1 || gender === '1') return '男';
      if (gender === 2 || gender === '2') return '女';
      if (gender === 0 || gender === '0') return '其他';
      return '';
    },

    // 处理详情按钮点击
    handleDetail(row) {
      this.showContentDetail(row);
    },
    formatGender(row, column) {
      if (row.gender === 1 || row.gender === '1') return '男';
      if (row.gender === 2 || row.gender === '2') return '女';
      if (row.gender === 0 || row.gender === '0') return '其他';
      return ''
    },
    
    // 格式化出生日期
    formatBirthday(row, column) {
      if (row.birthday) {
        return this.parseTime(row.birthday, '{y}-{m}-{d}');
      }
      return '';
    },
// 获取标签显示文字
    getApproveStatusLabel(value) {
      return this.approveStatusMap[value]?.label || '未知状态';
    },

    // 获取标签样式类型
    getApproveStatusTagType(value) {
      return this.approveStatusMap[value]?.type || 'warning';
    },

handleViewFile(fileUrl) {
  console.log('文件URL:', fileUrl);
  if (!fileUrl) {
    this.$message.warning('暂无附件信息');
    return;
  }
  const fullUrl = import.meta.env.VITE_APP_BASE_API + `/profile/download?fullPath=${fileUrl}`;
  console.log('完整下载路径:', fullUrl);
  const link = document.createElement('a');
  link.href = fullUrl;
  link.download = fileUrl.split('/').pop();
  link.target = '_blank'; // 关键修复
  link.click();
},
    
    // 处理审核操作
    handleApprove(row) {
      this.title = '审核结果';
      this.approveOpen = true;
      
      // 重置表单
      this.approveForm = {
        signupId: row.signupId,
        approveStatus: 1, // 默认通过
        approveReview: ''
      };
      
      // 如果需要获取已有审核信息
      getApprove(row.signupId).then(response => {
        if (response.data) {
          this.approveForm = {
            ...response.data,
            // 正确处理0值，只有当approveStatus严格等于null或undefined时才使用默认值1
            approveStatus: response.data.approveStatus !== null && response.data.approveStatus !== undefined
              ? response.data.approveStatus
              : 1
          };
        }
      }).catch(error => {
        console.error('获取审核信息失败:', error);
      });
    },
    
    // 提交审核表单
    submitApproveForm() {
      this.$refs.approveRef.validate(valid => {
        if (valid) {
          const formData = {...this.approveForm};
          formData.approveTime = new Date().getTime();
          
          updateApprove(formData).then(() => {
            this.$message.success('审核成功');
            this.approveOpen = false;
            this.getList(); // 刷新列表
          }).catch(error => {
            this.$message.error('审核失败: ' + error.message);
          });
        }
      });
    },
    
    // 取消审核
    cancelApprove() {
      this.approveOpen = false;
    },
    
    // 查看审核详情
    handleViewApproveInfo(row) {
      getApprove(row.signupId).then(response => {
        this.detailForm = {
          ...response.data,
          name: row.name
        };
        this.detailOpen = true;
      }).catch(error => {
        this.$message.error('获取审核信息失败: ' + error.message);
      });
    },
    
    // 解析时间
    parseTime(time, pattern) {
      if (!time) return '';
      const date = new Date(time);
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
      const o = {
        'y': date.getFullYear(),
        'm': date.getMonth() + 1,
        'd': date.getDate(),
        'h': date.getHours(),
        'i': date.getMinutes(),
        's': date.getSeconds(),
        'a': date.getDay()
      };
      const result = format.replace(/{(y|m|d|h|i|s|a)+}/g, (match, key) => {
        let value = o[key];
        if (key === 'a') return ['日', '一', '二', '三', '四', '五', '六'][value];
        if (match.length > 3 && value < 10) value = '0' + value;
        return value || 0;
      });
      return result;
    },
    
    /* 允许的最大行数 */
    MAX_LINES: 4,
    
    /* 通用的截断函数 */
    truncateLines(text) {
      const lines = text.replace(/\n+$/, '').split('\n');
      if (lines.length <= this.MAX_LINES) return text;
      return lines.slice(0, this.MAX_LINES).join('\n');
    },
    
    /* 1. 拦截键盘回车 */
    handleKeydown(e) {
      // Enter 键
      if (e.key === 'Enter') {
        const lines = (e.target.value + '\n').split('\n');
        // 如果已经有 4 行，就阻止默认行为
        if (lines.length > this.MAX_LINES) {
          e.preventDefault();
        }
      }
    },
    
    /* 2. 兜底：粘贴或 set 值时再截断 */
    handleInput(val) {
      const truncated = this.truncateLines(val);
      if (truncated !== val) {
        nextTick(() => {
          this.approveForm.approveReview = truncated;
        });
      }
    }
  }
}
</script>

<style scoped>
/* 操作列按钮样式优化 */
.el-table-column--fixed-right .el-button {
  margin-right: 8px;
  margin-bottom: 5px;
}

/* 表格行高调整 */
.el-table__row {
  height: 56px;
}

/* 搜索表单样式优化 */
.search-form {
  margin-bottom: 16px;
  padding: 10px;
}

/* 按钮悬停效果增强 */
.el-button:hover {
  opacity: 0.9;
  transform: translateY(-1px);
  transition: all 0.2s ease;
}

/* 审核状态标签样式调整 */
.el-tag {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
}

/* 按钮行样式 */
.mb8 {
  margin-bottom: 8px;
}
</style>